import { ref, computed, watchEffect, nextTick } from "vue";
import { PxMessageBox, PxMessage } from "px-ui";

import { querySystemTree } from "@/api/common";
import { querySystemSelect } from "@/api/equip/archive";
import { getListForRuleType } from "@/api/system/runningStatusSetting/ruleDesc";

export const useBaseInfo = form => {
  const defaultProps = {
    children: "children",
    label: "name",
    value: "code"
  };
  const classNameList = JSON.parse(localStorage.getItem("classList"));

  if (classNameList.length === 1) {
    form.value.className = classNameList[0].code;
  }

  const ruleTypeList = ref([]);
  const dialogVisible = ref(false);
  const allSystemList = ref<any[]>([]);
  const systemListForCondition = ref<any[]>([]);
  const selectedSystemCodeList = ref<string[]>([]);

  const filterSystemList = computed<any[]>(() => {
    if (allSystemList.value?.length > 0) return allSystemList.value;
    return systemListForCondition.value;
  });

  const getCodes = (node): string[] => {
    const codes = [node.code];
    if (node?.children?.length) {
      node.children.forEach(item => {
        codes.push(...getCodes(item));
      });
    }
    return codes;
  };

  const getNodeForSecondLevel = node => {
    let parentNode = node.parent;
    let parentNodeType = parentNode.data.type;

    while (parentNode && parentNodeType && parentNodeType !== "className") {
      parentNode = parentNode?.parent;
      parentNodeType = parentNode?.data?.type;
    }

    return parentNode;
  };

  const isAllSystemTreeItemType = (node: any) => {
    return "type" in node;
  };

  // 点击左侧树节点，获取工厂、科室、系统、系统codes
  const handleNodeClick = async (node, nodeData) => {
    if (isAllSystemTreeItemType(node)) {
      if (node.type === "className") {
        // 二级科室
        form.value.className = node.code;
        await nextTick();
        form.value.systemCode = "";
      } else if (node.type === "systemCategory") {
        // 三级及三级以下节点
        selectedSystemCodeList.value = getCodes(node);
        const nodeForSecondLevel = getNodeForSecondLevel(nodeData);
        form.value.className = nodeForSecondLevel.data.code;
      }
    } else {
      selectedSystemCodeList.value = getCodes(node);
    }
  };

  // 关闭子级设备dialog弹窗
  const closeEquipDialog = () => {
    dialogVisible.value = false;
  };

  // 改变设备编号
  const changeEqpId = equipDetail => {
    selectedSystemCodeList.value = [];
    form.value.className = equipDetail?.className || "";
    form.value.systemCode = equipDetail?.systemCode || "";
    form.value.eqpId = equipDetail?.eqpId || "";
    form.value.eqpName = equipDetail?.eqpName || "";
    form.value.eqpPosition = equipDetail?.positionNameAll || "";
    Object.keys(form.value).forEach(key => {
      const item = form.value[key];
      if (item?.eqpRunStatusPointList) {
        item.eqpRunStatusPointList = [];
        item.formula = "";
      }
    });
    getTypeList();
  };

  const classChanged = () => {
    form.value.systemCode = "";
    form.value.eqpId = "";
    form.value.eqpName = "";
    form.value.eqpPosition = "";
    form.value.ruleTypeCode = "";
    getTypeList();
  };

  const systemCodeChanged = () => {
    form.value.eqpId = "";
    form.value.eqpName = "";
    form.value.eqpPosition = "";
  };

  const getAllSystemTree = async () => {
    try {
      const res = await querySystemSelect({ className: form.value.className });
      if ((res as any[]).length) {
        allSystemList.value = res as any[];
        systemListForCondition.value = [];
      }
    } catch (err) {
      console.log("queryAllSystemTree error", err);
    }
  };

  const getSystemTreeByCondition = async () => {
    try {
      const res = await querySystemTree({ className: form.value.className });
      if ((res as any[]).length) {
        systemListForCondition.value = res as any[];
        allSystemList.value = [];
      }
    } catch (err) {
      console.log("querySystemTree error", err);
    }
  };

  const getTypeList = async () => {
    const params = {
      className: form.value.className
    };
    const data = await getListForRuleType(params);
    ruleTypeList.value = data.map(item => ({
      code: item.ruleTypeCode,
      name: item.ruleTypeName
    }));
  };

  getTypeList();

  watchEffect(() => {
    if (form.value.className) {
      getSystemTreeByCondition();
      return;
    }
    getAllSystemTree();
  });

  return {
    defaultProps,
    ruleTypeList,
    classNameList,
    dialogVisible,
    selectedSystemCodeList,
    filterSystemList,
    handleNodeClick,
    closeEquipDialog,
    changeEqpId,
    classChanged,
    systemCodeChanged
  };
};

export const useValidate = form => {
  const ruleInfo = {
    className: "请选择科室",
    systemCode: "请选择系统",
    eqpId: "请选择设备编号",
    eqpName: "请选择设备名称",
    eqpPosition: "请选择设备位置",
    ruleTypeCode: "请选择规则类型",
    "runRule.isEnabled": "请选择状态启用",
    "runRule.eqpRunStatusPointList": "请选择点位",
    "runRule.formula": "请输入规则",
    "awaitRule.isEnabled": "请选择状态启用",
    "awaitRule.eqpRunStatusPointList": "请选择点位",
    "awaitRule.formula": "请输入规则",
    "offlineRule.isEnabled": "请选择状态启用",
    "offlineRule.eqpRunStatusPointList": "请选择点位",
    "offlineRule.formula": "请输入规则",
    "diseaseRule.isEnabled": "请选择状态启用",
    "diseaseRule.eqpRunStatusPointList": "请选择点位",
    "diseaseRule.formula": "请输入规则",
    "faultRule.isEnabled": "请选择状态启用",
    "faultRule.eqpRunStatusPointList": "请选择点位",
    "faultRule.formula": "请输入规则",
    "meterCoerceRule.isEnabled": "请选择状态启用",
    "meterCoerceRule.eqpRunStatusPointList": "请选择点位",
    "meterCoerceRule.formula": "请输入规则",
    "sideSupplyRule.isEnabled": "请选择状态启用",
    "sideSupplyRule.eqpRunStatusPointList": "请选择点位",
    "sideSupplyRule.formula": "请输入规则"
  };

  function generateRequiredRules(obj, prefix = "") {
    const rules = {};

    Object.keys(obj).forEach(key => {
      const fullPath = prefix ? `${prefix}.${key}` : key;
      const value = obj[key];

      if (typeof value === "object" && value !== null && !Array.isArray(value)) {
        // 递归处理嵌套对象
        Object.assign(rules, generateRequiredRules(value, fullPath));
      } else {
        // 添加必填规则
        rules[fullPath] = [{ required: true, message: `${ruleInfo[fullPath]}`, trigger: "blur" }];
      }
    });

    return rules;
  }

  // 使用方式
  const rules = generateRequiredRules(form.value);

  return {
    rules
  };
};

export const usePointsSelect = form => {
  const showSelect = ref(false);
  let selectCode = "";
  const statusToPointMap: Map<string, Map<string, any>> = new Map();

  const handleDelete = (code, row) => {
    PxMessageBox.confirm(`确定删除该点位吗？`, "提示", {
      confirmButtonText: "确认删除",
      cancelButtonText: "取消",
      type: "warning",
      draggable: true
    })
      .then(() => {
        form.value[code].eqpRunStatusPointList = form.value[code].eqpRunStatusPointList.filter(point => point.id !== row.id);
      })
      .catch(() => {});
  };

  const handleSelectPoint = val => {
    if (!form.value.eqpId) {
      PxMessage.error("请选择设备");
      return;
    }
    selectCode = val;
    showSelect.value = true;
  };
  const selectCallback = rows => {
    if (rows?.length) {
      rows.forEach(row => {
        if (!statusToPointMap.get(selectCode)) {
          statusToPointMap.set(selectCode, new Map());
        }
        const idToPointMap = statusToPointMap.get(selectCode);
        if (!idToPointMap.get(row.id)) {
          idToPointMap.set(row.id, row);
          form.value[selectCode].eqpRunStatusPointList.push(row);
        }
      });
    }
  };
  const closeDialog = () => {
    showSelect.value = false;
  };

  return {
    showSelect,
    handleDelete,
    handleSelectPoint,
    selectCallback,
    closeDialog
  };
};
